package com.weai.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 * HTTP客户端工具类
 * 用于发送HTTP请求
 */
@Component
@Slf4j
public class HttpClientUtil {

    private final RestTemplate restTemplate;

    public HttpClientUtil() {
        this.restTemplate = new RestTemplate();
        // 添加UTF-8编码的消息转换器
        this.restTemplate.getMessageConverters()
                .add(0, new StringHttpMessageConverter(StandardCharsets.UTF_8));
    }

    /**
     * 发送POST请求，使用JSON格式的请求体
     *
     * @param url 请求URL
     * @param requestBody 请求体
     * @return 响应结果
     */
    public String postForJson(String url, Map<String, Object> requestBody) {
        HttpHeaders headers = new HttpHeaders();
        // 显式设置Content-Type为APPLICATION_JSON并指定UTF-8编码
        headers.setContentType(new MediaType(MediaType.APPLICATION_JSON.getType(),
                MediaType.APPLICATION_JSON.getSubtype(),
                StandardCharsets.UTF_8));
        
        HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(requestBody, headers);
        
        try {
            ResponseEntity<String> response = restTemplate.postForEntity(url, requestEntity, String.class);
            log.info("HTTP POST请求发送成功，URL: {}, 状态码: {}", url, response.getStatusCode());
            return response.getBody();
        } catch (Exception e) {
            log.error("HTTP POST请求发送失败，URL: {}, 错误信息: {}", url, e.getMessage(), e);
            throw e;
        }
    }
    
    /**
     * 发送GET请求
     *
     * @param url 请求URL
     * @return 响应结果
     */
    public String get(String url) {
        try {
            ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);
            log.info("HTTP GET请求发送成功，URL: {}, 状态码: {}", url, response.getStatusCode());
            return response.getBody();
        } catch (Exception e) {
            log.error("HTTP GET请求发送失败，URL: {}, 错误信息: {}", url, e.getMessage(), e);
            throw e;
        }
    }
} 